﻿using D.AT.Extensions;
using D.AT.Models;
using D.AT.UIUitl;
using System.Security.Principal;
using static System.Net.Mime.MediaTypeNames;

namespace D.AT
{
    public partial class FrmEvn : Form
    {
        public FrmEvn()
        {
            InitializeComponent();
            this.dgvEnvList.SetGridDataViewStyle();
            this.cboSPCDbType.SelectedIndexChanged += cboSPCDbType_SelectedIndexChanged;
            this.cboMESDbType.SelectedIndexChanged += cboMESDbType_SelectedIndexChanged;
        }

        /// <summary>
        /// 加载窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void FrmDb_Load(object sender, EventArgs e)
        {
            this.LoadColumn();

            this.cboSPCDbType.Items.Add("Orcale");
            this.cboSPCDbType.Items.Add("MySql");
            this.cboSPCDbType.Items.Add("PostgreSQL");
            this.cboSPCDbType.Items.Add("Redis");
            this.cboSPCDbType.Items.Add("MongoDB");
            this.cboSPCDbType.Items.Add("SqlServer");

            this.cboMESDbType.Items.Add("Orcale");
            this.cboMESDbType.Items.Add("MySql");
            this.cboMESDbType.Items.Add("PostgreSQL");
            this.cboMESDbType.Items.Add("Redis");
            this.cboMESDbType.Items.Add("MongoDB");
            this.cboMESDbType.Items.Add("SqlServer");

            this.cboSpcSidServiceName.Items.Add("SERVICE_NAME");
            this.cboSpcSidServiceName.Items.Add("SID");

            this.cboMesSidServiceName.Items.Add("SERVICE_NAME");
            this.cboMesSidServiceName.Items.Add("SID");

            await this.LoadEnvSettingsAsync();
        }

        /// <summary>
        /// 加载列
        /// </summary>
        private void LoadColumn()
        {
            DataGridViewTextBoxColumn idBoxColumn = new DataGridViewTextBoxColumn();
            idBoxColumn.ReadOnly = true;
            idBoxColumn.Name = "Id";
            idBoxColumn.HeaderText = "序号";
            idBoxColumn.DataPropertyName = "Id";
            dgvEnvList.Columns.Add(idBoxColumn);

            DataGridViewTextBoxColumn envNameBoxColumn = new DataGridViewTextBoxColumn();
            envNameBoxColumn.ReadOnly = true;
            envNameBoxColumn.Name = "Name";
            envNameBoxColumn.HeaderText = "名称";
            envNameBoxColumn.DataPropertyName = "Name";
            dgvEnvList.Columns.Add(envNameBoxColumn);

            DataGridViewTextBoxColumn ipBoxColumn = new DataGridViewTextBoxColumn();
            ipBoxColumn.ReadOnly = true;
            ipBoxColumn.Name = "Ip";
            ipBoxColumn.HeaderText = "IP";
            ipBoxColumn.DataPropertyName = "Ip";
            dgvEnvList.Columns.Add(ipBoxColumn);

            DataGridViewTextBoxColumn portBoxColumn = new DataGridViewTextBoxColumn();
            portBoxColumn.ReadOnly = true;
            portBoxColumn.Name = "Port";
            portBoxColumn.HeaderText = "端口";
            portBoxColumn.DataPropertyName = "Port";
            dgvEnvList.Columns.Add(portBoxColumn);

            DataGridViewTextBoxColumn spcDbTypeBoxColumn = new DataGridViewTextBoxColumn();
            spcDbTypeBoxColumn.ReadOnly = true;
            spcDbTypeBoxColumn.Name = "SPCDbType";
            spcDbTypeBoxColumn.HeaderText = "SPC-数据库类型";
            spcDbTypeBoxColumn.DataPropertyName = "SPCDbType";
            dgvEnvList.Columns.Add(spcDbTypeBoxColumn);


            DataGridViewTextBoxColumn spcAccountBoxColumn = new DataGridViewTextBoxColumn();
            spcAccountBoxColumn.ReadOnly = true;
            spcAccountBoxColumn.Name = "SPCAccount";
            spcAccountBoxColumn.HeaderText = "SPC-账户";
            spcAccountBoxColumn.DataPropertyName = "SPCAccount";
            dgvEnvList.Columns.Add(spcAccountBoxColumn);

            DataGridViewTextBoxColumn spcPwdBoxColumn = new DataGridViewTextBoxColumn();
            spcPwdBoxColumn.ReadOnly = true;
            spcPwdBoxColumn.Name = "SPCPwd";
            spcPwdBoxColumn.HeaderText = "SPC-密码";
            spcPwdBoxColumn.DataPropertyName = "SPCPwd";
            dgvEnvList.Columns.Add(spcPwdBoxColumn);

            DataGridViewTextBoxColumn spcSidOrServiceNameBoxColumn = new DataGridViewTextBoxColumn();
            spcSidOrServiceNameBoxColumn.ReadOnly = true;
            spcSidOrServiceNameBoxColumn.Name = "SPCSidOrServiceName";
            spcSidOrServiceNameBoxColumn.HeaderText = "SPC-SID/服务名";
            spcSidOrServiceNameBoxColumn.DataPropertyName = "SPCSidOrServiceName";
            dgvEnvList.Columns.Add(spcSidOrServiceNameBoxColumn);

            DataGridViewTextBoxColumn spcSidBoxColumn = new DataGridViewTextBoxColumn();
            spcSidBoxColumn.ReadOnly = true;
            spcSidBoxColumn.Name = "SPCSid";
            spcSidBoxColumn.HeaderText = "SPC-SID/服务名值";
            spcSidBoxColumn.DataPropertyName = "SPCSid";
            dgvEnvList.Columns.Add(spcSidBoxColumn);

            DataGridViewTextBoxColumn spcIpBoxColumn = new DataGridViewTextBoxColumn();
            spcIpBoxColumn.ReadOnly = true;
            spcIpBoxColumn.Name = "SPCIp";
            spcIpBoxColumn.HeaderText = "SPC-IP";
            spcIpBoxColumn.DataPropertyName = "SPCIp";
            dgvEnvList.Columns.Add(spcIpBoxColumn);

            DataGridViewTextBoxColumn spcPortBoxColumn = new DataGridViewTextBoxColumn();
            spcPortBoxColumn.ReadOnly = true;
            spcPortBoxColumn.Name = "SPCPort";
            spcPortBoxColumn.HeaderText = "SPC-端口";
            spcPortBoxColumn.DataPropertyName = "SPCPort";
            dgvEnvList.Columns.Add(spcPortBoxColumn);

            DataGridViewTextBoxColumn mesDbTypeBoxColumn = new DataGridViewTextBoxColumn();
            mesDbTypeBoxColumn.ReadOnly = true;
            mesDbTypeBoxColumn.Name = "MESDbType";
            mesDbTypeBoxColumn.HeaderText = "MES-数据库类型";
            mesDbTypeBoxColumn.DataPropertyName = "MESDbType";
            dgvEnvList.Columns.Add(mesDbTypeBoxColumn);

            DataGridViewTextBoxColumn mesAccountBoxColumn = new DataGridViewTextBoxColumn();
            mesAccountBoxColumn.ReadOnly = true;
            mesAccountBoxColumn.Name = "MESAccount";
            mesAccountBoxColumn.HeaderText = "MES-账户";
            mesAccountBoxColumn.DataPropertyName = "MESAccount";
            dgvEnvList.Columns.Add(mesAccountBoxColumn);

            DataGridViewTextBoxColumn mesPwdBoxColumn = new DataGridViewTextBoxColumn();
            mesPwdBoxColumn.ReadOnly = true;
            mesPwdBoxColumn.Name = "MESPwd";
            mesPwdBoxColumn.HeaderText = "MES-密码";
            mesPwdBoxColumn.DataPropertyName = "MESPwd";
            dgvEnvList.Columns.Add(mesPwdBoxColumn);

            DataGridViewTextBoxColumn mesSidOrServiceNameBoxColumn = new DataGridViewTextBoxColumn();
            mesSidOrServiceNameBoxColumn.ReadOnly = true;
            mesSidOrServiceNameBoxColumn.Name = "MESSidOrServiceName";
            mesSidOrServiceNameBoxColumn.HeaderText = "MES-SID/服务名";
            mesSidOrServiceNameBoxColumn.DataPropertyName = "MESSidOrServiceName";
            dgvEnvList.Columns.Add(mesSidOrServiceNameBoxColumn);

            DataGridViewTextBoxColumn mesSidBoxColumn = new DataGridViewTextBoxColumn();
            mesSidBoxColumn.ReadOnly = true;
            mesSidBoxColumn.Name = "MESSid";
            mesSidBoxColumn.HeaderText = "MES-SID/服务名值";
            mesSidBoxColumn.DataPropertyName = "MESSid";
            dgvEnvList.Columns.Add(mesSidBoxColumn);

            DataGridViewTextBoxColumn mesIpBoxColumn = new DataGridViewTextBoxColumn();
            mesIpBoxColumn.ReadOnly = true;
            mesIpBoxColumn.Name = "MESIp";
            mesIpBoxColumn.HeaderText = "MES-IP";
            mesIpBoxColumn.DataPropertyName = "MESIp";
            dgvEnvList.Columns.Add(mesIpBoxColumn);

            DataGridViewTextBoxColumn mesPortBoxColumn = new DataGridViewTextBoxColumn();
            mesPortBoxColumn.ReadOnly = true;
            mesPortBoxColumn.Name = "MESPort";
            mesPortBoxColumn.HeaderText = "MES-端口";
            mesPortBoxColumn.DataPropertyName = "MESPort";
            dgvEnvList.Columns.Add(mesPortBoxColumn);

            DataGridViewTextBoxColumn ocapIpBoxColumn = new DataGridViewTextBoxColumn();
            ocapIpBoxColumn.ReadOnly = true;
            ocapIpBoxColumn.Name = "OCAPIp";
            ocapIpBoxColumn.HeaderText = "OCAP-IP";
            ocapIpBoxColumn.DataPropertyName = "OCAPIp";
            dgvEnvList.Columns.Add(ocapIpBoxColumn);

            DataGridViewTextBoxColumn ocapPortBoxColumn = new DataGridViewTextBoxColumn();
            ocapPortBoxColumn.ReadOnly = true;
            ocapPortBoxColumn.Name = "OCAPPort";
            ocapPortBoxColumn.HeaderText = "OCAP-端口";
            ocapPortBoxColumn.DataPropertyName = "OCAPPort";
            dgvEnvList.Columns.Add(ocapPortBoxColumn);

            DataGridViewTextBoxColumn xAccessSecretBoxColumn = new DataGridViewTextBoxColumn();
            xAccessSecretBoxColumn.ReadOnly = true;
            xAccessSecretBoxColumn.Name = "XAccessSecret";
            xAccessSecretBoxColumn.HeaderText = "OCAP-令牌";
            xAccessSecretBoxColumn.DataPropertyName = "XAccessSecret";
            dgvEnvList.Columns.Add(xAccessSecretBoxColumn);

            DataGridViewButtonColumn delBoxColumn = new DataGridViewButtonColumn();
            delBoxColumn.ReadOnly = true;
            delBoxColumn.Name = "Delete";
            delBoxColumn.HeaderText = "操作";
            delBoxColumn.DefaultCellStyle.NullValue = "删除";
            dgvEnvList.Columns.Add(delBoxColumn);
        }

        /// <summary>
        /// 加载表格数据
        /// </summary>
        /// <returns></returns>
        private async Task LoadEnvSettingsAsync()
        {
            var entities = await OrmFactory.MySqllite.Select<EnvSettingEntity>().ToListAsync();
            this.dgvEnvList.DataSource = entities;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnSave_Click(object sender, EventArgs e)
        {
            var evnEntities = new EnvSettingEntity()
            {
                Name = txtName.Text,
                Ip = txtIp.Text,
                Port = txtPort.Text,

                SPCAccount = txtSPCAccount.Text,
                SPCPwd = txtSPCPwd.Text,
                SPCDbType = cboSPCDbType.Text,
                SPCSid = txtSPCSID.Text,
                SPCIp = txtSPCIP.Text,
                SPCPort = txtSPCPort.Text,
                SPCSidOrServiceName = cboSpcSidServiceName.Text,

                MESAccount = txtMESAccount.Text,
                MESPwd = txtMESPwd.Text,
                MESDbType = cboMESDbType.Text,
                MESSid = txtMESSID.Text,
                MESIp = txtMESIP.Text,
                MESPort = txtMESPort.Text,
                MESSidOrServiceName = cboMesSidServiceName.Text,
                OCAPIp = txtOCAPIp.Text,
                OCAPPort = txtOCAPPort.Text,
                XAccessSecret = txtXAccessSecret.Text,
            };

            var dbEntity = await OrmFactory.MySqllite.Select<EnvSettingEntity>().Where(m => m.Name == evnEntities.Name).FirstAsync();
            if (dbEntity != null)
            {// 修改
                evnEntities.Id = dbEntity.Id;
                var updateRes = await OrmFactory.MySqllite.Update<EnvSettingEntity>().SetSource(evnEntities).ExecuteAffrowsAsync();
                if (updateRes > 0)
                {
                    MessageBox.Show("修改成功");
                    await this.LoadEnvSettingsAsync();
                }
                else
                {
                    MessageBox.Show("修改失败");
                }
            }
            else
            {// 新增
                var insertRes = await OrmFactory.MySqllite.Insert<EnvSettingEntity>(evnEntities).ExecuteAffrowsAsync();
                if (insertRes > 0)
                {
                    MessageBox.Show("新增成功");
                    await this.LoadEnvSettingsAsync();
                }
                else
                {
                    MessageBox.Show("新增失败");
                }
            }
        }

        /// <summary>
        /// 选择某一行后
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvEnvList_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvEnvList.SelectedRows.Count == 1)
            {
                txtName.Text = dgvEnvList.SelectedRows[0].Cells["Name"].Value?.ToString();
                txtIp.Text = dgvEnvList.SelectedRows[0].Cells["Ip"].Value?.ToString();
                txtPort.Text = dgvEnvList.SelectedRows[0].Cells["Port"].Value?.ToString();

                txtSPCAccount.Text = dgvEnvList.SelectedRows[0].Cells["SPCAccount"].Value?.ToString();
                txtSPCPwd.Text = dgvEnvList.SelectedRows[0].Cells["SPCPwd"].Value?.ToString();
                txtSPCIP.Text = dgvEnvList.SelectedRows[0].Cells["SPCIp"].Value?.ToString();
                txtSPCPort.Text = dgvEnvList.SelectedRows[0].Cells["SPCPort"].Value?.ToString();
                txtSPCSID.Text = dgvEnvList.SelectedRows[0].Cells["SPCSid"].Value?.ToString();
                if (dgvEnvList.SelectedRows[0].Cells["SPCSidOrServiceName"].Value != null)
                {
                    cboSpcSidServiceName.SelectedItem = dgvEnvList.SelectedRows[0].Cells["SPCSidOrServiceName"].Value?.ToString();
                }

                var spcDbType = dgvEnvList.SelectedRows[0].Cells["SPCDbType"].Value?.ToString();

                if (spcDbType == "Orcale")
                {//Orcale
                    cboSPCDbType.SelectedIndex = 0;
                }
                else if (spcDbType == "MySql")
                {//MySql
                    cboSPCDbType.SelectedIndex = 1;
                }
                else if (spcDbType == "PostgreSQL")
                {//PostgreSQL
                    cboSPCDbType.SelectedIndex = 2;
                }
                else if (spcDbType == "Redis")
                {//Redis
                    cboSPCDbType.SelectedIndex = 3;
                }
                else if (spcDbType == "MongoDB")
                {//MongoDB
                    cboSPCDbType.SelectedIndex = 4;
                }
                else if (spcDbType == "SqlServer")
                {//SqlServer
                    cboSPCDbType.SelectedIndex = 5;
                }

                txtOCAPIp.Text = dgvEnvList.SelectedRows[0].Cells["OCAPIp"].Value?.ToString();
                txtOCAPPort.Text = dgvEnvList.SelectedRows[0].Cells["OCAPPort"].Value?.ToString();
                txtXAccessSecret.Text = dgvEnvList.SelectedRows[0].Cells["XAccessSecret"].Value?.ToString();

                txtMESAccount.Text = dgvEnvList.SelectedRows[0].Cells["MESAccount"].Value?.ToString();
                txtMESPwd.Text = dgvEnvList.SelectedRows[0].Cells["MESPwd"].Value?.ToString();
                txtMESIP.Text = dgvEnvList.SelectedRows[0].Cells["MESIp"].Value?.ToString();
                txtMESPort.Text = dgvEnvList.SelectedRows[0].Cells["MESPort"].Value?.ToString();
                txtMESSID.Text = dgvEnvList.SelectedRows[0].Cells["MESSid"].Value?.ToString();
                if (dgvEnvList.SelectedRows[0].Cells["MESSidOrServiceName"].Value != null)
                {
                    cboMesSidServiceName.SelectedItem = dgvEnvList.SelectedRows[0].Cells["MESSidOrServiceName"].Value?.ToString();
                }
                var mesDbType = dgvEnvList.SelectedRows[0].Cells["MESDbType"].Value?.ToString();

                if (mesDbType == "Orcale")
                {//Orcale
                    cboMESDbType.SelectedIndex = 0;
                }
                else if (mesDbType == "MySql")
                {//MySql
                    cboMESDbType.SelectedIndex = 1;
                }
                else if (mesDbType == "PostgreSQL")
                {//PostgreSQL
                    cboMESDbType.SelectedIndex = 2;
                }
                else if (mesDbType == "Redis")
                {//Redis
                    cboMESDbType.SelectedIndex = 3;
                }
                else if (mesDbType == "MongoDB")
                {//MongoDB
                    cboMESDbType.SelectedIndex = 4;
                }
                else if (mesDbType == "SqlServer")
                {//SqlServer
                    cboMESDbType.SelectedIndex = 5;
                }
            }
        }

        /// <summary>
        /// 改变数据库类型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboSPCDbType_SelectedIndexChanged(object? sender, EventArgs e)
        {
            if (cboSPCDbType.SelectedIndex == 0)
            {//Orcale
                this.txtSPCPort.Text = "1521";
            }
            else if (cboSPCDbType.SelectedIndex == 1)
            {//MySql
                this.txtSPCPort.Text = "3306";
            }
            else if (cboSPCDbType.SelectedIndex == 2)
            {//PostgreSQL
                this.txtSPCPort.Text = "5432";
            }
            else if (cboSPCDbType.SelectedIndex == 3)
            {//Redis
                this.txtSPCPort.Text = "6379";
            }
            else if (cboSPCDbType.SelectedIndex == 4)
            {//MongoDB
                this.txtSPCPort.Text = "27017";
            }
            else if (cboSPCDbType.SelectedIndex == 5)
            {//SqlServer
                this.txtSPCPort.Text = "1433";
            }
        }

        /// <summary>
        /// 改变数据库类型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboMESDbType_SelectedIndexChanged(object? sender, EventArgs e)
        {
            if (cboMESDbType.SelectedIndex == 0)
            {//Orcale
                this.txtMESPort.Text = "1521";
            }
            else if (cboMESDbType.SelectedIndex == 1)
            {//MySql
                this.txtMESPort.Text = "3306";
            }
            else if (cboMESDbType.SelectedIndex == 2)
            {//PostgreSQL
                this.txtMESPort.Text = "5432";
            }
            else if (cboMESDbType.SelectedIndex == 3)
            {//Redis
                this.txtMESPort.Text = "6379";
            }
            else if (cboMESDbType.SelectedIndex == 4)
            {//MongoDB
                this.txtMESPort.Text = "27017";
            }
            else if (cboMESDbType.SelectedIndex == 5)
            {//SqlServer
                this.txtMESPort.Text = "1433";
            }
        }

        /// <summary>
        /// 点击删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void dgvEnvList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvEnvList.Columns[e.ColumnIndex].Name == "Delete")
            {
                //点击第一行button按钮事件
                int index = dgvEnvList.SelectedCells[0].RowIndex;

                var name = dgvEnvList.SelectedRows[0].Cells["Name"].Value.ToString();
                var processEntity = await OrmFactory.MySqllite.Select<ProcessEntity>().Where(m => m.EvnName == name).FirstAsync();
                if (processEntity != null)
                {
                    MessageBox.Show($"禁止删除，有工作[{processEntity.Name}]正在使用"); return;
                }

                //获取所在行的值
                var id = int.Parse(dgvEnvList.SelectedRows[0].Cells["Id"].Value.ToString());
                // 删除
                var deleteRes = await OrmFactory.MySqllite.Delete<EnvSettingEntity>().Where(m => m.Id == id).ExecuteAffrowsAsync();
                if (deleteRes > 0)
                {
                    MessageBox.Show("删除成功");
                    await this.LoadEnvSettingsAsync();
                }
                else
                {
                    MessageBox.Show("删除失败");
                }
            }
        }
    }
}
